<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\common\model\Auth;
use app\user\model\User as UserModel;
use app\mill\model\Client as ClientModel;
use app\mill\model\Contract as ContractModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Log as LogModel;
use app\admin\model\Config as ConfigModel;
use think\Db;

/**
 * 工程合同控制器
 * @package app\admin\controller
 */
class Contract extends Admin
{

    /**
     * 客户列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function client()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('mill_client')
            ->alias('c')
            ->field('c.*')
            ->leftJoin('mill_order o','o.client_id=c.id')
            ->where($map)
            ->group('c.id')
            ->order('c.id desc')
            ->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('客户列表（客户数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_client') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'c.company', '客户公司', 'like'],
                ['text:2', 'c.mobile', '客户联系电话', 'like'],
                ['text:2', 'c.back', '跟单人员', 'like'],
                ['text:2', 'c.sales', '销售经理', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '客户序号'],
                ['company', '客户公司'],
                ['nickname', '客户联系人'],
                ['mobile', '客户联系电话'],
                ['address', '客户地址'],
                ['sales', '销售经理'],
                ['sales_mobile', '销售电话'],
                ['back', '跟单人员'],
                ['note', '备注','popover'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('index', ['title' => '查看合同', 'href' => url('mill/contract/index')."?_s=client_id=__id__&_o=client_id=eq", 'icon' => ''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 80,
                'sales_mobile'  => 80,
                'address'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 合同列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $is_contract = true;
        if(!empty($map)){
            foreach ($map as $k=>$v){
                if(($v[0] == 'o.engineering' && !empty($v[2])) || ($v[0] == 'o.order_sn' && !empty($v[2])))$is_contract = false;
            }
        }
        if($is_contract)$map[] = ['o.contract','eq',''];
        sort($map);
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,cc.id,cc.status,cc.status_verify_uid,cc.create_time as contract_time,cc.again_status,cc.again_status_note,cc.status_note')
            ->where($map)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->group('o.order_pid')
            ->order('cc.create_time desc,o.id desc')
            ->paginate()
            ->each(function ($v){

                $v['batch'] = Db::name('mill_order')->where(['order_pid'=>$v['order_pid'],'archives_status'=>2])->count();
                $v['status_verify_uid'] = intval($v['status_verify_uid']);
                $v['status'] = intval($v['status']);
                if(!is_numeric($v['again_status']))$v['again_status'] = 1;

                return $v;
            })
        ;

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('合同管理') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.order_sn', '工程编号', 'like'],
                ['select:2', 'client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'c.sales', '销售经理', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['client_id2','客户公司','','',$company],
                ['order_sn', '工程编号'],
                ['engineering', '工程名称'],
                ['batch','批次数量'],
                ['client_id','销售经理',ClientModel::getSalesList()],
                //['money_str', '订金'],
                ['contract','合同','callback',function($value, $data){
                    if(empty($data['contract_time']))$value = '无';
                    else $value = '有';
                    return $value;
                },'__data__'],
                ['status_verify_uid','审核人',UserModel::getList()],
                ['back', '内勤'],
                ['contract_time', '合同签订日期','date'],
                ['note', '备注','popover'],
                ['status','状态','callback',function($value, $data){
                    $value = intval($value);
                    //复审
                    $text = '';
                    $note = $data['status_note'];
                    if($data['again_status'] != 1){
                        $value = $data['again_status'];
                        $text = '复审';
                        $note = $data['again_status_note'];
                    }
                    $status = OrderModel::status_tag($value,$text.ContractModel::$status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$note.'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('show',['title' => '合同预览','href' => url('show',['id' => '__id__']),'icon'=>''],['area' => ['50%', '90%'], 'title' => ['合同预览', 'font-size:24px;text-align: center;']])
            ->addRightButton('edit',['title' => '编辑','href' => url('mill/contract/add',['order_id' => '__order_pid__']),'class'=>'btn btn-default','icon'=>''])
            ->addRightButton('prints',['title' => '打印','href' => admin_url('prints',['id'=>'__id__']),'class'=>'btn btn-default','icon'=>'','target'=>'_blank'])
            ->addRightButton('again',['title' => '申请修改','href' => admin_url('again',['id'=>'__id__']),'class'=>'btn btn-default ajax-get confirm','icon'=>''])

            ->replaceRightButton(['status' => ['>','1']],'',['edit'])
            ->replaceRightButton(['again_status' => ['<>','1']],'',['again'])
            ->replaceRightButton(['status' => ['<','2']],'',['prints','again'])

            //->replaceRightButton(['status' => ['>','2']],'',['edit'])
            //->replaceRightButton(['again_status' => ['<>','2']],'',['again'])
            //->replaceRightButton(['status' => ['<>','3']],'',['prints','again'])

            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'money_str'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        $order_id = input('order_id');
        $contract = Db::name('mill_order_contract')
            ->alias('cc')
            ->field('cc.*,o.engineering,o.engineering_full,o.order_sn,c.company,c.sales')
            ->leftJoin('mill_order o','o.id=cc.order_id')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where(['cc.order_id'=>$order_id])
            ->find();
        if(!empty($contract)){
            $order = $contract;
            $order['contract'] = json_decode($order['contract'],true);
            $order['finance_config'] = json_decode($order['finance_config'],true);
        }
        else{
            $order = Db::name('mill_order')
                ->alias('o')
                ->field('o.*,o.id as order_id,c.company,c.sales')
                ->leftJoin('mill_client c','c.id=o.client_id')
                ->where(['o.id'=>$order_id])
                ->find();
            $order_sn = $order['order_sn'];
            if(empty($order_sn))$order_sn = OrderModel::orderSn($order_id);

            $order['contract_sn'] = "SWAXY".date('Ymd')."-{$order['id']}";
            $order['order_sn'] = $order_sn;
            $order['note'] = '';
            $order['address_nickname'] = '';
            $order['address_mobile'] = '';
            $order['compile'] = get_nickname(UID);
            $order['contract'] = '';
            $order['group_verify'] = '';
            $order['authority_verify'] = '';
            $order['handler'] = '';
            $order['director'] = '';
            $order['director_mobile'] = '';
            $order['spec'] = '详见铝板加工图';
            $order['area'] = '';
            $order['finance_type'] = '';
            $order['finance_money'] = '';
            $order['late_money'] = '';
            $order['late_time'] = '';
            $order['finance_config'] = '';
            $order['create_time'] = time();
            $order['update_time'] = time();
        }

        if ($this->request->isPost()) {
            $data = input();
            if(empty($data['contract']))$this->error('合同服务不能为空');
            if(empty($data['finance_config']))$data['finance_config'] = [];
            unset($data['__token__']);

            foreach ($data['contract'] as $rk=>$rv){
                foreach ($rv as &$rvv){
                    if(strpos($rvv,'input') !== false){

                        //获取input值，并拼接
                        $val = $data['contract_input'][$rk][$rvv];
                        //拼接该多选的值
                        $val_arr = explode('input',$rvv);
                        $rvv = "";

                        foreach ($val_arr as $vak=>$vav){
                            $rvv_val = "";
                            if(!empty($val[$vak]))$rvv_val = $val[$vak];
                            $rvv .= "{$vav}{$rvv_val}";

                        }
                    }
                }
                $data['contract'][$rk] = $rv;
            }

            $data['contract'] = json_encode($data['contract'],JSON_UNESCAPED_UNICODE);
            $data['finance_config'] = json_encode($data['finance_config'],JSON_UNESCAPED_UNICODE);
            $data['status'] = 3;
            $data['update_time'] = time();

            $order_update = [
                'engineering'           =>  $data['engineering'],
                'engineering_full'      =>  $data['engineering_full'],
                'order_sn'              =>  $data['order_sn'],
            ];
            unset($data['engineering']);
            unset($data['engineering_full']);
            unset($data['order_sn']);

            if(!empty($contract)){
                $data['id'] = $contract['id'];
                $re = ContractModel::update($data);
            }
            else $re = ContractModel::create($data);
            if ($re) {

                Db::name('mill_order')->where(['id'=>$data['order_id']])->update($order_update);

                $id = $re['id'];
                //$this->success('操作成功', admin_url('prints',['id'=>$id]) ,'_blank');
                $this->success('操作成功', cookie('__forward__'));
            }
            $this->error('操作失败');
        }

        $table_arr = ContractModel::fromTabale($order);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        $js = '<script type="text/javascript">
                $(function() {
                    $("input[name=\'finance_type\']").click(function() {
                        var val = $(this).val();
                        $(".finance").hide();
                        $(".finance").removeClass("hidden");
                        $(".finance[data-type=\'"+val+"\']").show();
                    });
                })
            </script>';

        $info = [];
        return ZBuilder::make('form')
            ->setPageTitle('编辑合同') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['complexTable:12', 'contract', '', $table_data, $table_head],
            ])
            ->setExtraJs($js)
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 编辑
     * @param null $id
     * @return mixed
     */
    public function edit($id=null)
    {
        return $this->add();
    }
    /**
     * 打印
     * @param null $id
     * @return mixed
     */
    public function prints()
    {

        $id = input('param.id');

        $data = Db::name('mill_order_contract')
            ->alias('s')
            ->field('s.*,o.order_sn,o.engineering,o.create_time as contract_date,c.company,c.sales,o.engineering_full')
            ->leftJoin('mill_order o','o.id=s.order_id')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where(['s.id'=>$id])
            ->find();
        $data['contract'] = json_decode($data['contract'],true);
        $data['finance_config'] = json_decode($data['finance_config'],true);

        $html = ContractModel::toHtml($data);

        exit($html);
    }
    /**
     * 删除
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }
    /**
     * 启用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }
    /**
     * 禁用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }
    /**
     * 待审核工程列表页
     * @return mixed
     */
    public function examine()
    {

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['cc.status','in','-1,1'];

        //待审核
        $map0[] = ['cc.status','eq','1'];
        $total0 = Db::name('mill_order')
            ->alias('o')
            ->where($map0)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->count();
        //未通过
        $map01[] = ['cc.status','eq','-1'];
        $total01 = Db::name('mill_order')
            ->alias('o')
            ->where($map01)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->count();
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,cc.id,cc.status,cc.status_verify_uid,cc.create_time as contract_time,cc.again_status,cc.again_status_note,cc.status_note')
            ->where($map)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->group('o.order_pid')
            ->order('o.id desc')
            ->paginate()
            ->each(function ($v){

                $v['batch'] = Db::name('mill_order')->where(['order_pid'=>$v['order_pid'],'archives_status'=>2])->count();
                $v['status_verify_uid'] = intval($v['status_verify_uid']);
                $v['status'] = intval($v['status']);
                if(!is_numeric($v['again_status']))$v['again_status'] = 1;

                return $v;
            })
        ;

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("合同审核（待审核{$total0}/未通过{$total01}）") // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.order_sn', '工程编号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'c.sales', '销售经理', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['client_id2','客户公司','','',$company],
                ['order_sn', '工程编号'],
                ['engineering', '工程名称'],
                ['batch','批次数量'],
                ['client_id','销售经理',ClientModel::getSalesList()],
                //['money_str', '订金'],
                ['contract','合同','callback',function($value, $data){
                    if(empty($data['contract_time']))$value = '无';
                    else $value = '有';
                    return $value;
                },'__data__'],
                ['status_verify_uid','审核人',UserModel::getList()],
                ['back', '内勤'],
                ['contract_time', '合同签订日期','date'],
                ['note', '备注','popover'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,contractModel::$status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('show',['title' => '合同预览','href' => url('show',['id' => '__id__']),'icon'=>''],['area' => ['50%', '90%'], 'title' => ['合同预览', 'font-size:24px;text-align: center;']])
            ->addRightButton('enable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__'])."?fieldv=status|2",'icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['status' => ['in', '2']], '', 'enable,notDisable')

            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'money_str'  => 60,
            ])
            ->fetch(); // 渲染模板


    }
    /**
     * 待审核工程列表页，付款方式
     * @return mixed
     */
    public function examinePrice()
    {

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['cc.status','in','-1,2'];

        //待审核
        $map0[] = ['cc.status','eq','2'];
        $total0 = Db::name('mill_order')
            ->alias('o')
            ->where($map0)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->count();
        //未通过
        $map01[] = ['cc.status','eq','-1'];
        $total01 = Db::name('mill_order')
            ->alias('o')
            ->where($map01)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->count();
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,cc.id,cc.status,cc.status_verify_uid,cc.create_time as contract_time,cc.again_status,cc.again_status_note,cc.status_note')
            ->where($map)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->group('o.order_pid')
            ->order('o.id desc')
            ->paginate()
            ->each(function ($v){

                $v['batch'] = Db::name('mill_order')->where(['order_pid'=>$v['order_pid'],'archives_status'=>2])->count();
                $v['status_verify_uid'] = intval($v['status_verify_uid']);
                $v['status'] = intval($v['status']);
                if(!is_numeric($v['again_status']))$v['again_status'] = 1;

                return $v;
            })
        ;

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("合同审核（待审核{$total0}/未通过{$total01}）") // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.order_sn', '工程编号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'c.sales', '销售经理', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['client_id2','客户公司','','',$company],
                ['order_sn', '工程编号'],
                ['engineering', '工程名称'],
                ['batch','批次数量'],
                ['client_id','销售经理',ClientModel::getSalesList()],
                //['money_str', '订金'],
                ['contract','合同','callback',function($value, $data){
                    if(empty($data['contract_time']))$value = '无';
                    else $value = '有';
                    return $value;
                },'__data__'],
                ['status_verify_uid','审核人',UserModel::getList()],
                ['back', '内勤'],
                ['contract_time', '合同签订日期','date'],
                ['note', '备注','popover'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,contractModel::$status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('show',['title' => '合同预览','href' => url('show',['id' => '__id__']),'icon'=>''],['area' => ['50%', '90%'], 'title' => ['合同预览', 'font-size:24px;text-align: center;']])
            ->addRightButton('enable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__'])."?fieldv=status|3",'icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['status' => ['in', '3']], '', 'enable,notDisable')

            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'money_str'  => 60,
            ])
            ->fetch(); // 渲染模板


    }
    /**
     * 审核
     */
    public function backEnable()
    {

        $id = input('param.id');
        $fieldv = input('param.fieldv');
        $fieldv_arr = explode('@',$fieldv);
        foreach ($fieldv_arr as $v){

            $info = ContractModel::where('id', $id)->find();
            $info['order_sn'] = Db::name('mill_order')->where(['id'=>$info['order_id']])->value('order_sn');

            $v = explode('|',$v);
            if (false === ContractModel::where('id', $id)->setField($v[0], $v[1])) {
                $this->error('审核失败，工程ID：'.$id);
            }
            //审核人员
            ContractModel::where('id', $id)->setField($v[0].'_verify_uid', UID);
            //审核时间
            ContractModel::where('id', $id)->setField($v[0].'_time', time());

            //更新工程审核状态
            if($v[0] == 'status'){
                //审核人员
                ContractModel::where('id', $id)->setField('group_verify', get_nickname(UID));

                if($v[1] != 3){
                    $order_id = Db::name('mill_order_contract')->where(['id'=>$id])->value('order_id');
                    $order_field = "back_{$v[0]}";
                    OrderModel::where('id', $order_id)->setField($order_field, $v[1]);
                    //审核人员
                    OrderModel::where('id', $order_id)->setField($order_field.'_verify_uid', UID);
                    //审核时间
                    OrderModel::where('id', $order_id)->setField($order_field.'_time', time());
                }

                //推送消息
                $status_str = '审核';
                if($v['1'] == 0)$status_str = '复审';
                elseif($v['1'] == 3)$status_str = '财务部审核';
                $content = "工程编号<span class='text-primary'>[{$info['order_sn']}]</span>{$status_str}通过";
                $href = admin_url('index')."?_s=o.order_sn={$info['order_sn']}&_o=o.order_sn=like";
                //LogModel::send_message("合同{$status_str}",$content,$href);

            }
        }

        $this->success('提交成功', null, '_parent_reload');
    }
    /**
     * 审核不通过
     */
    public function notDisable()
    {
        $field = input('param.field');
        if ($this->request->isPost()) {
            $data = input();
            $id = input('param.id');
            if (false === ContractModel::where('id', $id)->setField($field, -1)) {
                $this->error('审核失败，工程ID：'.$id);
            }
            if(!empty($data[$field.'_note']))ContractModel::where('id', $id)->setField($field.'_note', $data[$field.'_note']);
            //审核人员
            ContractModel::where('id', $id)->setField($field.'_verify_uid', UID);

            $this->success('操作成功', null, '_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('审核不通过原因') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['textarea', $field.'_note', '[:请输入审核不通过原因]'],
            ])
            ->layout([$field.'_note'=>12])
            ->fetch();
    }
    /**
     * 申请修改
     */
    public function again()
    {

        $id = input('param.id');

        $where = ['id'=>$id];

        $contract_sn = Db::name('mill_order_contract')->where($where)->value('contract_sn');
        $model = 'mill_order_contract';
        $remark = "操作人员：".get_nickname(UID)."，申请修改样品单，样品编号：{$contract_sn}";

        LogModel::addLog($id,$model,1,$remark);

        $add = [
            'again_status'  =>  0,
        ];
        Db::name('mill_order_contract')->where($where)->update($add);

        $this->success('提交成功');
    }
    /**
     * 申请修改列表页
     * @return mixed
     */
    public function againList()
    {

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['cc.again_status','in','-1,0'];

        //待审核
        $map0[] = ['cc.again_status','eq','0'];
        $total0 = Db::name('mill_order')
            ->alias('o')
            ->where($map0)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->count();
        //未通过
        $map01[] = ['cc.again_status','eq','-1'];
        $total01 = Db::name('mill_order')
            ->alias('o')
            ->where($map01)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->count();
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,cc.id,cc.status,cc.status_verify_uid,cc.create_time as contract_time,cc.again_status,cc.again_status_note,cc.status_note')
            ->where($map)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->group('o.order_pid')
            ->order('o.id desc')
            ->paginate()
            ->each(function ($v){

                $v['batch'] = Db::name('mill_order')->where(['order_pid'=>$v['order_pid'],'archives_status'=>2])->count();
                $v['status_verify_uid'] = intval($v['status_verify_uid']);
                $v['status'] = intval($v['status']);
                if(!is_numeric($v['again_status']))$v['again_status'] = 1;

                return $v;
            })
        ;

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("合同审核（待审核{$total0}/未通过{$total01}）") // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.order_sn', '工程编号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'c.sales', '销售经理', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['client_id2','客户公司','','',$company],
                ['order_sn', '工程编号'],
                ['engineering', '工程名称'],
                ['batch','批次数量'],
                ['client_id','销售经理',ClientModel::getSalesList()],
                //['money_str', '订金'],
                ['contract','合同','callback',function($value, $data){
                    if(empty($data['contract_time']))$value = '无';
                    else $value = '有';
                    return $value;
                },'__data__'],
                ['status_verify_uid','审核人',UserModel::getList()],
                ['back', '内勤'],
                ['contract_time', '合同签订日期','date'],
                ['note', '备注','popover'],
                ['again_status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['again_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('show',['title' => '合同预览','href' => url('show',['id' => '__id__']),'icon'=>''],['area' => ['50%', '90%'], 'title' => ['合同预览', 'font-size:24px;text-align: center;']])
            ->addRightButton('enable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__'])."?fieldv=again_status|1@status|0",'icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'again_status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['again_status' => ['in', '1']], '', 'enable,notDisable')

            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'money_str'  => 60,
            ])
            ->fetch(); // 渲染模板


    }
    /**
     * 合同浏览
     * @return mixed
     */
    public function show()
    {

        $id = input('param.id');
        if(empty($id))$this->error('暂无合同');

        $data = Db::name('mill_order_contract')
            ->alias('s')
            ->field('s.*,o.order_sn,o.engineering,o.create_time as contract_date,c.company,c.sales,o.engineering_full')
            ->leftJoin('mill_order o','o.id=s.order_id')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where(['s.id'=>$id])
            ->find();
        $data['contract'] = json_decode($data['contract'],true);
        $data['finance_config'] = json_decode($data['finance_config'],true);

        $html = ContractModel::toHtml($data,2);

        $html = str_replace('window.print();',"",$html);

        exit($html);
    }
    /**
     * 合同浏览
     * @return mixed
     */
    public function show2(){

        return $this->show();
    }
}
